package cn.turboinfo.fuyang.api.domain.admin.usecase.dictconfig;

import cn.turboinfo.fuyang.api.domain.common.service.dictconfig.DictConfigItemService;
import cn.turboinfo.fuyang.api.domain.common.service.dictconfig.DictConfigService;
import cn.turboinfo.fuyang.api.domain.common.usecase.AbstractUseCase;
import cn.turboinfo.fuyang.api.entity.common.pojo.dictconfig.DictConfig;
import cn.turboinfo.fuyang.api.entity.common.pojo.dictconfig.DictConfigItem;
import lombok.Builder;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.Optional;

@Slf4j
@RequiredArgsConstructor
@Component
public class DictConfigItemCheckAvailableUseCase extends AbstractUseCase<DictConfigItemCheckAvailableUseCase.InputData, DictConfigItemCheckAvailableUseCase.OutputData> {
    private final DictConfigService dictConfigService;

    private final DictConfigItemService dictConfigItemService;

    @Override
    protected OutputData doAction(InputData inputData) {

        Long id = inputData.getItemId();

        Long dictId = inputData.getDictId();

        String itemValue = inputData.getItemValue();

        if (id != null && id > 0) {
            Optional<DictConfigItem> optional = dictConfigItemService.getById(id);
            if (optional.isPresent()) {
                DictConfigItem item = optional.get();
                if (item.getDictConfigId().equals(dictId) && item.getItemValue().equals(itemValue)) {
                    // 可以维持使用自身的不做变动
                    return OutputData.builder()
                            .available(true)
                            .build();
                }
            } else {
                return OutputData.builder()
                        .available(false)
                        .build();
            }
        }
        DictConfig dictConfig = dictConfigService.getByIdEnsure(dictId);
        boolean available = dictConfigItemService.getDictConfigItem(dictConfig.getDictKey(), itemValue).isEmpty();

        return OutputData.builder()
                .available(available)
                .build();
    }

    @Getter
    @Setter
    @Builder
    public static class InputData extends AbstractUseCase.InputData {

        private Long itemId;

        @NotNull(
                message = "字典 ID 不能为空"
        )
        private Long dictId;

        @NotBlank(
                message = "条目值不能为空"
        )
        private String itemValue;

    }

    @Getter
    @Setter
    @Builder
    public static class OutputData extends AbstractUseCase.OutputData {
        private boolean available;
    }
}
